﻿using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using NX5Web.Entities;
using JWT.Builder;
using NX5Web.Utils;

namespace NX5Web.Filters
{
    public class ApiAuthorizeAttribute: AuthorizeAttribute
    {
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {

            // 检查Controller和Action是否标记ApiAuthorize ..
            var apiAuthorize = actionContext.ActionDescriptor.ControllerDescriptor
                .GetCustomAttributes<ApiAuthorizeAttribute>().Any()
                || actionContext.ActionDescriptor
                .GetCustomAttributes<ApiAuthorizeAttribute>().Any();

            if (apiAuthorize)
            {
                var auth = actionContext.Request.Headers.Authorization;
                if (auth?.Scheme == "Bearer")
                {
                    var token = auth.Parameter;
                    if (string.IsNullOrEmpty(token))
                    {
                        return false;
                    }

                    // 验证Token
                    var principal = JwtHelper.ValidateToken(auth.Parameter);
                    // 规则1：设置到当前请求上下文
                    actionContext.RequestContext.Principal = principal;
                    // 规则2：同步到HttpContext
                    HttpContext.Current.User = principal;

                    return true;
                }
                return false;
            }

            return true;
        }

        // 处理授权失败的请求
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            var erModel = new ApiHttpRequest()
            {
                status = false,
                message = "身份认证不正确！"
            };
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, erModel, "application/json");
        }
    }
}